<template>
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="dynamic-form">
        <el-form-item v-for="field in model.fields" :key="field.name" :label="field.label" :prop="field.name">
            <!-- 字符串/文本输入 -->
            <el-input
                v-if="field.type === 'string'"
                v-model="form[field.name]"
                :placeholder="field.placeholder || `请输入${field.label}`"
                :disabled="field.disabled"
            />

            <!-- 多行文本 -->
            <el-input
                v-else-if="field.type === 'text'"
                v-model="form[field.name]"
                type="textarea"
                :rows="field.rows || 4"
                :placeholder="field.placeholder || `请输入${field.label}`"
                :disabled="field.disabled"
            />

            <!-- 数字输入 -->
            <el-input-number
                v-else-if="field.type === 'number'"
                v-model="form[field.name]"
                :min="field.min"
                :max="field.max"
                :step="field.step || 1"
                :placeholder="field.placeholder || `请输入${field.label}`"
                :disabled="field.disabled"
            />

            <!-- 布尔值开关 -->
            <el-switch
                v-else-if="field.type === 'boolean'"
                v-model="form[field.name]"
                :disabled="field.disabled"
            />

            <!-- 日期选择器 -->
            <el-date-picker
                v-else-if="field.type === 'date'"
                v-model="form[field.name]"
                type="date"
                :placeholder="field.placeholder || `请选择${field.label}`"
                :disabled="field.disabled"
            />

            <!-- 日期时间选择器 -->
            <el-date-picker
                v-else-if="field.type === 'datetime'"
                v-model="form[field.name]"
                type="datetime"
                :placeholder="field.placeholder || `请选择${field.label}`"
                :disabled="field.disabled"
            />

            <!-- 下拉选择框 -->
            <el-select
                v-else-if="field.type === 'select'"
                v-model="form[field.name]"
                :placeholder="field.placeholder || `请选择${field.label}`"
                :disabled="field.disabled"
            >
                <el-option
                    v-for="option in field.options || []"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                />
            </el-select>

            <!-- 单选框组 -->
            <el-radio-group
                v-else-if="field.type === 'radio'"
                v-model="form[field.name]"
                :disabled="field.disabled"
            >
                <el-radio
                    v-for="option in field.options || []"
                    :key="option.value"
                    :label="option.value"
                >
                    {{ option.label }}
                </el-radio>
            </el-radio-group>

            <!-- 多选框组 -->
            <el-checkbox-group
                v-else-if="field.type === 'checkbox'"
                v-model="form[field.name]"
                :disabled="field.disabled"
            >
                <el-checkbox
                    v-for="option in field.options || []"
                    :key="option.value"
                    :label="option.value"
                >
                    {{ option.label }}
                </el-checkbox>
            </el-checkbox-group>

            <!-- 文件上传 -->
            <el-upload
                v-else-if="field.type === 'upload'"
                :action="field.uploadUrl || '/api/upload'"
                :disabled="field.disabled"
                :limit="field.limit || 1"
                :multiple="field.multiple || false"
                :on-success="handleUploadSuccess"
                :file-list="form[field.name] || []"
            >
                <el-button type="primary">点击上传</el-button>
            </el-upload>

            <!-- 未知类型显示 -->
            <div v-else class="text-red-500">未知字段类型: {{ field.type }}</div>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="submit" :loading="loading">提交</el-button>
            <el-button @click="resetForm" class="ml-2">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

// 定义props
const props = defineProps({
    modelName: {
        type: String,
        required: true
    },
    id: {
        type: String,
        required: false
    },
    // 表单初始值
    initialValues: {
        type: Object,
        default: () => ({})
    }
})

// 响应式变量
const model = ref({ fields: [] })
const form = ref({})
const rules = ref({})
const formRef = ref()
const loading = ref(false)
const emit = defineEmits(['success', 'error'])

// 加载模型元数据
const loadModel = async () => {
    try {
        loading.value = true
        model.value = await axios
            .get(`/metadata/models/${props.modelName}`)
            .then(res => res.data)

        // 构建校验规则和表单初始值
        model.value.fields.forEach(field => {
            // 初始化表单值
            form.value[field.name] = props.initialValues[field.name] !== undefined
                ? props.initialValues[field.name]
                : (field.defaultValue !== undefined ? field.defaultValue : '')

            // 构建校验规则
            if (field.required) {
                rules.value[field.name] = [{ required: true, message: `${field.label}必填` }]
            }

            // 添加其他校验规则
            if (field.pattern) {
                (rules.value[field.name] ||= []).push({
                    pattern: field.pattern,
                    message: field.patternMessage || `${field.label}格式不正确`
                })
            }

            if (field.minLength) {
                (rules.value[field.name] ||= []).push({
                    min: field.minLength,
                    message: `${field.label}长度不能少于${field.minLength}个字符`
                })
            }

            if (field.maxLength) {
                (rules.value[field.name] ||= []).push({
                    max: field.maxLength,
                    message: `${field.label}长度不能超过${field.maxLength}个字符`
                })
            }

            if (field.min) {
                (rules.value[field.name] ||= []).push({
                    type: 'number',
                    min: field.min,
                    message: `${field.label}不能小于${field.min}`
                })
            }

            if (field.max) {
                (rules.value[field.name] ||= []).push({
                    type: 'number',
                    max: field.max,
                    message: `${field.label}不能大于${field.max}`
                })
            }
        })

        // 编辑时加载数据
        if (props.id && !Object.keys(props.initialValues).length) {
            const data = await axios
                .get(`/data/${props.modelName}/${props.id}`)
                .then(res => res.data)
            Object.assign(form.value, data)
        }
    } catch (error) {
        ElMessage.error(`加载模型失败: ${(error as any).message}`)
        emit('error', error)
    } finally {
        loading.value = false
    }
}

// 表单提交
const submit = async () => {
    try {
        await formRef.value.validate()
        loading.value = true

        if (props.id) {
            await axios.put(`/data/${props.modelName}/${props.id}`, form.value)
            ElMessage.success('更新成功')
        } else {
            await axios.post(`/data/${props.modelName}`, form.value)
            ElMessage.success('创建成功')
        }

        emit('success', form.value)
    } catch (error) {
        ElMessage.error(`提交失败: ${(error as any).message}`)
        emit('error', error)
    } finally {
        loading.value = false
    }
};

// 重置表单
const resetForm = () => {
    formRef.value.resetFields()
};

// 处理文件上传成功
const handleUploadSuccess = (response: any, uploadFile: any, uploadFiles: any) => {
    // 这里假设上传成功后返回的response包含文件URL
    // 根据实际后端接口调整
    if (response.success) {
        form.value[uploadFile.field] = uploadFiles
        ElMessage.success('上传成功')
    } else {
        ElMessage.error(`上传失败: ${response.message || '未知错误'}`)
    }
};

// 初始化和监听模型变化
onMounted(loadModel)
watch(() => props.modelName, loadModel)
watch(() => props.id, loadModel)
</script>

<style scoped>
.dynamic-form {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 表单项间距 */
.el-form-item {
  margin-bottom: 20px;
}

/* 单选框和多选框组样式 */
.el-radio-group,
.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

/* 文件上传样式 */
.el-upload {
  display: block;
  margin-top: 6px;
}

/* 按钮样式 */
.el-form-item__content {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .dynamic-form {
    padding: 16px;
  }

  .el-form {
    label-width: 80px;
  }

  .el-form-item__label {
    font-size: 14px;
  }
}

/* 暗黑模式适配 */
.dark .dynamic-form {
  background-color: var(--el-bg-color-dark);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
}

/* 错误提示样式 */
.text-red-500 {
  color: var(--el-color-danger);
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
}
</style>